package com.jindy.module.syAccountStatement.service.impl;

import com.jindy.common.constant.Constants;
import com.jindy.common.core.domain.AjaxResult;
import com.jindy.common.core.domain.model.LoginUser;
import com.jindy.common.exception.base.BaseException;
import com.jindy.common.utils.DateUtils;
import com.jindy.common.utils.SecurityUtils;
import com.jindy.common.utils.StringUtils;
import com.jindy.jpush.utils.UniJpushUtils;
import com.jindy.module.approvalConfig.domain.ApprovalConfig;
import com.jindy.module.approvalConfig.mapper.ApprovalConfigMapper;
import com.jindy.module.approvalRecord.domain.ApprovalRecord;
import com.jindy.module.approvalRecord.mapper.ApprovalRecordMapper;
import com.jindy.module.jpush.mapper.JpushMapper;
import com.jindy.module.serialNum.service.ISySerialNumTService;
import com.jindy.module.syAccountStatement.domain.SyAccountStatement;
import com.jindy.module.syAccountStatement.mapper.SyAccountStatementMapper;
import com.jindy.module.syAccountStatement.service.ISyAccountStatementService;
import com.jindy.module.syTableRecord.service.ISyTableRecordTService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 新对账单Service业务层处理
 * 
 * @author jindy
 * @date 2023-05-27
 */
@Service
public class SyAccountStatementServiceImpl implements ISyAccountStatementService 
{
    private static final Logger LOGGER = LoggerFactory.getLogger(SyAccountStatementServiceImpl.class);
    @Resource
    private SyAccountStatementMapper syAccountStatementMapper;

    /**
     * 生成流水单号Service
     */
    @Resource
    private ISySerialNumTService serialNumTService;

    /**
     * 审批记录
     */
    @Resource
    private ApprovalRecordMapper approvalRecordMapper;

    /**
     * 审批记录配置信息
     */
    @Resource
    private ApprovalConfigMapper approvalConfigMapper;

    /**
     * 设备id配置表
     */
    @Resource
    private JpushMapper jpushMapper;

    /**
     * 表设置
     */
    @Resource
    private ISyTableRecordTService iSyTableRecordTService;

    /**
     * 查询新对账单
     * 
     * @param id 新对账单主键
     * @return 新对账单
     */
    @Override
    public SyAccountStatement selectSyAccountStatementById(Long id)
    {
        return syAccountStatementMapper.selectSyAccountStatementById(id);
    }

    /**
     * 查询新对账单列表
     * 
     * @param syAccountStatement 新对账单
     * @return 新对账单
     */
    @Override
    public List<SyAccountStatement> selectSyAccountStatementList(SyAccountStatement syAccountStatement)
    {
        return syAccountStatementMapper.selectSyAccountStatementList(syAccountStatement);
    }

    /**
     * 新增新对账单
     * 
     * @param syAccountStatement 新对账单
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public AjaxResult insertSyAccountStatement(SyAccountStatement syAccountStatement)
    {
        // 获取当前人
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if (loginUser == null) {
            throw new BaseException("请先登录");
        }
        // 判断是否再提交
        if (null==syAccountStatement.getId()){
            // 生成流水单号
            String serialNum = serialNumTService.generateSerialNum("DZD");
            if (StringUtils.isBlank(serialNum)) {
                throw new BaseException("新增对账单审批-获取对账单单号失败");
            }
            syAccountStatement.setSerialNum(serialNum);
            syAccountStatement.setCreateTime(DateUtils.getNowDate());
            syAccountStatement.setBusinessStatus(Constants.APPROVE);
            syAccountStatementMapper.insertSyAccountStatement(syAccountStatement);
        }else{
            syAccountStatement.setUpdateTime(DateUtils.parseDate(DateUtils.getTime()));
            syAccountStatement.setUpdateBy(loginUser.getUsername());
            syAccountStatement.setBusinessStatus(Constants.APPROVE);
            updateSyAccountStatement(syAccountStatement);
            //删除审批记录
            approvalRecordMapper.deleteApprovalRecordBySerialNum(syAccountStatement.getSerialNum());
        }
        iSyTableRecordTService.saveEntityAndTable(syAccountStatement,syAccountStatement.getSerialNum());
        // 新增审批记录
        List<Long> addJpushList= addApprovalRecord(syAccountStatement);
        sendApproveMessage(addJpushList);
        return AjaxResult.success();
    }

    /**
     * 给审批人推送消息
     * @param addJpushList
     */
    private void sendApproveMessage(List<Long> addJpushList) {
        try {
            List<String> addRegIds = jpushMapper.selectRegistrationIdsByUserIds(addJpushList);
            if (!CollectionUtils.isEmpty(addRegIds)){
                UniJpushUtils.sendApproveMessage(addRegIds);
            }
        } catch (Exception e) {
            LOGGER.error("开票申请审批人推送通知失败",e);
        }
    }


    /**
     * 添加审批流程记录
     *
     * @param syAccountStatement
     */
    @Transactional(rollbackFor = Exception.class)
    public List<Long> addApprovalRecord(SyAccountStatement syAccountStatement) {
        // 消息推送人员
        List<Long> jpushList = new ArrayList<>();
        int sequence = 1;
        //  发起人
        ApprovalRecord firstApprovalRecord = getApprovalRecord(syAccountStatement);
        firstApprovalRecord.setSequence(sequence);
        firstApprovalRecord.setApprovalStatus(Constants.COMPLETED);
        firstApprovalRecord.setTypeOperation(Constants.AGREE);
        firstApprovalRecord.setBusinessStatus(Constants.APPROVE);
        firstApprovalRecord.setApproverId(Long.valueOf(syAccountStatement.getApplyUserId()));
        firstApprovalRecord.setApproverName(syAccountStatement.getApplyUserName());
        approvalRecordMapper.insertApprovalRecord(firstApprovalRecord);

        sequence++;
        //  默认周总
        List<ApprovalConfig> approvalConfigList = approvalConfigMapper.selectApprovalConfigList(new ApprovalConfig("DZD-LEADER", "1"));
        if (CollectionUtils.isEmpty(approvalConfigList)) {
            throw new RuntimeException("请检查审批配置信息：DZD-LEADER");
        }
        jpushList.add(approvalConfigList.get(0).getUserId());
        addApprovalConfig(sequence, approvalConfigList,syAccountStatement);

        sequence++;
        //  范雯雯
        List<ApprovalConfig> thirdApprovalConfigList = approvalConfigMapper.selectApprovalConfigList(new ApprovalConfig("DZD-CW", "1"));
        if (CollectionUtils.isEmpty(thirdApprovalConfigList)) {
            throw new RuntimeException("请检查审批配置信息：DZD-CW");
        }
        addApprovalConfig(sequence, thirdApprovalConfigList,syAccountStatement);

        sequence++;
        //  陈亚情
        List<ApprovalConfig> fourApprovalConfigList = approvalConfigMapper.selectApprovalConfigList(new ApprovalConfig("DZD-YQ", "1"));
        if (CollectionUtils.isEmpty(thirdApprovalConfigList)) {
            throw new RuntimeException("请检查审批配置信息：DZD-YQ");
        }
        addApprovalConfig(sequence, fourApprovalConfigList,syAccountStatement);
        return jpushList;
    }

    /**
     * 新增第二，第三审批记录信息
     *
     * @param sequence
     * @param approvalConfigList
     */
    @Transactional(rollbackFor = Exception.class)
    public void addApprovalConfig(int sequence, List<ApprovalConfig> approvalConfigList,SyAccountStatement syAccountStatement) {
        String status = Constants.NOT_APPROVED;
        if (sequence == 2) {
            status = Constants.APPROVE;
        }
        for (ApprovalConfig approvalConfig : approvalConfigList) {
            ApprovalRecord approvalRecord = getApprovalRecord(syAccountStatement);
            approvalRecord.setSequence(sequence);
            approvalRecord.setApprovalStatus(status);
            approvalRecord.setApproverId(approvalConfig.getUserId());
            approvalRecord.setApproverName(approvalConfig.getUsername());
            approvalRecordMapper.insertApprovalRecord(approvalRecord);
        }
    }

    /**
     * 获取审批记录对象
     *
     * @param syAccountStatement
     * @return
     */
    private ApprovalRecord getApprovalRecord(SyAccountStatement syAccountStatement) {
        ApprovalRecord approvalRecord = new ApprovalRecord();
        approvalRecord.setSerialNum(syAccountStatement.getSerialNum());
        approvalRecord.setUserId(Long.valueOf(syAccountStatement.getApplyUserId()));
        approvalRecord.setOrderId(syAccountStatement.getId());
        approvalRecord.setUserName(syAccountStatement.getApplyUserName());
        approvalRecord.setUpdateTime(DateUtils.parseDate(DateUtils.getTime()));
        approvalRecord.setUpdateBy(syAccountStatement.getApplyUserName());
        approvalRecord.setCreateBy(syAccountStatement.getApplyUserName());
        approvalRecord.setCreateTime(DateUtils.parseDate(DateUtils.getTime()));
        return approvalRecord;
    }

    /**
     * 修改新对账单
     * 
     * @param syAccountStatement 新对账单
     * @return 结果
     */
    @Override
    public int updateSyAccountStatement(SyAccountStatement syAccountStatement)
    {
        syAccountStatement.setUpdateTime(DateUtils.getNowDate());
        return syAccountStatementMapper.updateSyAccountStatement(syAccountStatement);
    }

    /**
     * 批量删除新对账单
     * 
     * @param ids 需要删除的新对账单主键
     * @return 结果
     */
    @Override
    public int deleteSyAccountStatementByIds(Long[] ids)
    {
        return syAccountStatementMapper.deleteSyAccountStatementByIds(ids);
    }

    /**
     * 删除新对账单信息
     * 
     * @param id 新对账单主键
     * @return 结果
     */
    @Override
    public int deleteSyAccountStatementById(Long id)
    {
        return syAccountStatementMapper.deleteSyAccountStatementById(id);
    }
}
